package com.shuo.limit.aspect;

import com.shuo.limit.algorithm.TimeWindowAlgorithm;
import com.shuo.limit.annotation.RateLimit;
import com.shuo.limit.aspect.util.RateKeyGenerator;
import com.simba.exception.BussException;
import com.simba.framework.util.common.ServerUtil;
import com.simba.framework.util.request.RequestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by shuoGG on 2018/9/29 0029
 */
@Aspect
@Component
public class TwndMethodAspect {

    private static final Log logger = LogFactory.getLog(TwndMethodAspect.class);

    @Autowired
    private TimeWindowAlgorithm algorithm;

    @Autowired
    private RateKeyGenerator keyGen;

    @Pointcut("@annotation(rateLimit)")
    public void annotationPointcut(RateLimit rateLimit) {
    }

    @Before("annotationPointcut(rateLimit)")
    public void doBefore(JoinPoint joinPoint, RateLimit rateLimit) throws IOException {
        String key = keyGen.getKey(rateLimit.type(), joinPoint);
        key = key + ":twnd";
        boolean isOk = algorithm.checkAllow(key, rateLimit.limit(), rateLimit.intervalSec());
        if (!isOk) {
            throw new BussException("客户端IP" + ServerUtil.getProxyIp(RequestUtil.getRequest()) + "访问太频繁");
        }
    }

}
